// 题目数据结构
class Question {
    constructor(id, text, options, correctAnswer, explanation, image = null, type = 'single') {
        this.id = id; // 题目ID
        this.text = text; // 题目内容
        this.options = options; // 选项数组
        this.correctAnswer = correctAnswer; // 正确答案
        this.explanation = explanation; // 解析
        this.image = image; // 图片路径（可选）
        this.type = type; // 题目类型：single-单选，multiple-多选
    }
}

// 应用主类
class NetworkBibleApp {
    constructor() {
        this.questions = []; // 所有题目
        this.currentQuestionIndex = 0; // 当前题目索引
        this.userAnswers = {}; // 用户答案记录
        this.isSubmitted = false; // 是否已提交答案
        this.wrongQuestions = []; // 错题记录
        this.wrongQuestionDetails = []; // 错题详细信息
        this.isExamMode = false; // 是否为考试模式
        this.examTimeLimit = 0; // 考试时间限制（分钟）
        this.examStartTime = null; // 考试开始时间
        this.examTimer = null; // 考试计时器
        this.appSettings = this.loadAppSettings(); // 应用设置
        this.init();
    }

    // 初始化应用
    init() {
        this.loadQuestionBanksFromFiles();
        this.bindEvents();
        this.showScreen('welcome');
    }

    // 绑定事件
    bindEvents() {
        // 导航按钮事件
        document.getElementById('practice-btn').addEventListener('click', () => {
            this.startPractice();
        });

        document.getElementById('mock-btn').addEventListener('click', () => {
            this.showScreen('exam-setup');
        });

        document.getElementById('wrong-btn').addEventListener('click', () => {
            this.showWrongQuestions();
        });

        document.getElementById('import-btn').addEventListener('click', () => {
            this.showScreen('import-screen');
            this.refreshQuestionBanksList();
        });

        // 模拟考试相关事件
        document.getElementById('start-exam').addEventListener('click', () => {
            this.showScreen('exam-setup');
        });

        document.getElementById('start-exam-confirm').addEventListener('click', () => {
            this.startExam();
        });

        document.getElementById('back-to-welcome').addEventListener('click', () => {
            this.showScreen('welcome');
        });

        document.getElementById('submit-exam').addEventListener('click', () => {
            this.submitExam();
        });

        // 返回主菜单按钮
        document.getElementById('back-to-main').addEventListener('click', () => {
            this.showScreen('welcome');
        });

        // 欢迎界面按钮
        document.getElementById('start-practice').addEventListener('click', () => {
            this.startPractice();
        });

        // 题目界面按钮
        document.getElementById('prev-btn').addEventListener('click', () => {
            this.prevQuestion();
        });

        document.getElementById('next-btn').addEventListener('click', () => {
            this.nextQuestion();
        });

        // 结果界面按钮
        document.getElementById('review-wrong').addEventListener('click', () => {
            this.showWrongQuestions();
        });

        document.getElementById('restart-btn').addEventListener('click', () => {
            this.showScreen('welcome');
        });

        // 导入界面按钮
        document.getElementById('import-submit').addEventListener('click', () => {
            this.importQuestions();
        });

        document.getElementById('load-sample').addEventListener('click', () => {
            this.loadQuestionBanksFromFiles();
            this.showImportResult('已从文件加载题库！', 'success');
        });

        document.getElementById('refresh-banks').addEventListener('click', () => {
            this.refreshQuestionBanksList();
        });

        document.getElementById('delete-bank').addEventListener('click', () => {
            this.deleteSelectedQuestionBank();
        });

        document.getElementById('rename-bank').addEventListener('click', () => {
            this.renameSelectedQuestionBank();
        });

        // 数据管理相关事件
        document.getElementById('export-all-data').addEventListener('click', () => {
            this.exportAllData();
        });

        document.getElementById('import-all-data').addEventListener('click', () => {
            document.getElementById('import-file-input').click();
        });

        document.getElementById('import-file-input').addEventListener('change', (e) => {
            if (e.target.files.length > 0) {
                this.importAllData(e.target.files[0]);
            }
        });

        document.getElementById('clear-all-data').addEventListener('click', () => {
            this.clearAllData();
        });

        // 错题本相关事件
        document.getElementById('practice-wrong').addEventListener('click', () => {
            this.practiceWrongQuestions();
        });

        document.getElementById('clear-wrong').addEventListener('click', () => {
            this.clearWrongQuestions();
        });

        document.getElementById('export-wrong').addEventListener('click', () => {
            this.exportWrongQuestions();
        });

        // 键盘快捷键
        document.addEventListener('keydown', (e) => {
            this.handleKeyboardShortcuts(e);
        });
    }

    // 显示指定屏幕
    showScreen(screenId) {
        // 隐藏所有屏幕
        document.querySelectorAll('.screen').forEach(screen => {
            screen.classList.add('hidden');
        });

        // 显示指定屏幕
        document.getElementById(screenId).classList.remove('hidden');
    }

    // 从文件加载题库数据
    async loadQuestionBanksFromFiles() {
        try {
            // 尝试加载默认题库文件
            const defaultFiles = [
                'data/network_2020_complete.json',
                'data/network_2020_h2.json',
                'data/network_2020.json',
                'data/questions.txt'
            ];

            for (const filePath of defaultFiles) {
                try {
                    const response = await fetch(filePath);
                    if (response.ok) {
                        const data = await response.json();
                        if (Array.isArray(data) && data.length > 0) {
                            // 生成题库名称
                            const bankName = this.generateQuestionBankName(data);
                            
                            // 保存到本地存储
                            this.saveQuestionBank(bankName, data);
                            
                            // 如果当前没有题目，加载第一个题库
                            if (this.questions.length === 0) {
                                this.questions = data;
                            }
                            
                            console.log(`成功加载题库文件: ${filePath}`);
                        }
                    }
                } catch (error) {
                    console.log(`无法加载文件 ${filePath}:`, error.message);
                }
            }

            // 如果没有加载到任何题库，使用示例数据
            if (this.questions.length === 0) {
                this.loadSampleData();
            }
        } catch (error) {
            console.error('加载题库文件失败:', error);
            // 如果所有文件加载失败，使用示例数据
            this.loadSampleData();
        }
    }

    // 加载示例数据（作为备用）
    loadSampleData() {
        // 添加一些示例题目
        this.questions = [
            new Question(
                1,
                '在支持多线程的操作系统中，假设进程P创建了线程T1，T2，T3，那么下列说法中，正确的是（ ）。',
                [
                    'A. 该进程中已打开的文件是不能被T1，T2和T3共享的',
                    'B. 该进程中T1的栈指针是不能被T2共享，但可被T3共享',
                    'C. 该进程中T1的栈指针是不能被T2和T3共享的',
                    'D. 该进程中某线程的栈指针是可以被T1，T2和T3共享的'
                ],
                'C',
                '线程共享的内容包括：进程代码段、进程的公有数据、进程打开的文件描述符、信号的处理器、进程的当前目录、进程用户ID与进程组ID。线程独有的内容包括：线程ID、寄存器组的值、线程的堆栈、错误返回码、线程的信号屏蔽码。'
            ),
            new Question(
                2,
                '假设某计算机的字长为32位，该计算机文件管理系统磁盘空间管理采用位示图，记录磁盘的使用情况，若磁盘的容量为300GB，物理块的大小为4MB，那么位示图的大小为（  ）字节。',
                [
                    'A. 2400',
                    'B. 3200',
                    'C. 6400',
                    'D. 9600'
                ],
                'D',
                '本题考查操作系统中的空闲块管理方法——位示图。题目指出磁盘容量为：300G，物理盘大小是4MB。则物理盘块个数为：300GB/4MB=75×1024。每个物理盘块占用1个bit位来标识磁盘有没有被占用，系统中1个字是32位，所以字的个数：（75×1024）/32=2400。换成字节是9600。'
            ),
            new Question(
                3,
                '微内核，描述不正确的是（ ）。',
                [
                    'A. 微内核系统结构清晰，利于提供系统灵活性',
                    'B. 微内核代码量少，有良好的移植性',
                    'C. 微内核有良好的伸缩，拓展性',
                    'D. 微内核功能代码可以相互调用，性能高'
                ],
                'D',
                '本题考查微内核操作系统的知识。微内核相比于传统内核，效率较差。D选项的叙述是错误。采用微内核结构的操作系统与传统的操作系统相比，其优点是提高了系统的灵活性、可扩充性，增强了系统的可靠性，提供了对分布式系统的支持。'
            ),
            new Question(
                4,
                '下图展示了网络拓扑结构，请根据图示选择正确的描述（ ）。',
                [
                    'A. 这是一个星型网络拓扑',
                    'B. 这是一个环型网络拓扑',
                    'C. 这是一个总线型网络拓扑',
                    'D. 这是一个网状网络拓扑'
                ],
                'A',
                '根据图片显示，所有设备都连接到一个中心节点，这是典型的星型网络拓扑结构。',
                'images/sample_question.png'
            )
        ];
    }

    // 开始练习
    startPractice() {
        if (this.questions.length === 0) {
            alert('暂无题目，请先导入题目数据！');
            return;
        }

        this.currentQuestionIndex = 0;
        this.userAnswers = {};
        this.showQuestion();
        this.showScreen('question-screen');
    }

    // 显示当前题目
    showQuestion() {
        const question = this.questions[this.currentQuestionIndex];
        const totalCount = this.questions.length;

        // 更新题目信息
        document.getElementById('question-count').textContent = `第${this.currentQuestionIndex + 1}题 / 共${totalCount}题`;
        document.getElementById('question-type').textContent = question.type === 'single' ? '单选题' : '多选题';
        document.getElementById('question-text').textContent = question.text;

        // 更新进度条
        this.updateProgress();

        // 处理图片
        const imageContainer = document.getElementById('question-image');
        if (question.image) {
            this.displayQuestionImage(question.image, imageContainer);
        } else {
            imageContainer.classList.add('hidden');
        }

        // 生成选项
        const optionsContainer = document.getElementById('options-container');
        optionsContainer.innerHTML = '';
        question.options.forEach(option => {
            const optionElement = document.createElement('div');
            optionElement.className = 'option';
            optionElement.textContent = option;
            optionElement.dataset.option = option.charAt(0); // 获取选项字母(A, B, C, D)

            // 如果用户已作答，显示相应状态
            if (this.userAnswers[question.id]) {
                const userAnswer = this.userAnswers[question.id];
                if (userAnswer.includes(option.charAt(0))) {
                    optionElement.classList.add('selected');
                }
            }

            // 添加点击事件
            optionElement.addEventListener('click', () => {
                if (question.type === 'single') {
                    // 单选题逻辑
                    document.querySelectorAll('.option').forEach(opt => {
                        opt.classList.remove('selected');
                    });
                    optionElement.classList.add('selected');
                    this.userAnswers[question.id] = [optionElement.dataset.option];
                    
                    // 单选题立即检查答案
                    setTimeout(() => {
                        this.checkAnswer(question);
                    }, 100);
                } else {
                    // 多选题逻辑
                    optionElement.classList.toggle('selected');
                    if (!this.userAnswers[question.id]) {
                        this.userAnswers[question.id] = [];
                    }

                    const optionIndex = this.userAnswers[question.id].indexOf(optionElement.dataset.option);
                    if (optionIndex > -1) {
                        this.userAnswers[question.id].splice(optionIndex, 1);
                    } else {
                        this.userAnswers[question.id].push(optionElement.dataset.option);
                    }
                    
                    // 多选题需要检查是否选择了足够的选项
                    this.checkMultipleChoiceAnswer(question);
                }
            });

            optionsContainer.appendChild(optionElement);
        });

        // 更新按钮状态
        document.getElementById('prev-btn').disabled = this.currentQuestionIndex === 0;
        document.getElementById('next-btn').disabled = this.currentQuestionIndex === totalCount - 1;
        
        // 考试模式下显示提交按钮
        const submitBtn = document.getElementById('submit-exam');
        if (this.isExamMode) {
            submitBtn.classList.remove('hidden');
        } else {
            submitBtn.classList.add('hidden');
        }
    }

    // 上一题
    prevQuestion() {
        if (this.currentQuestionIndex > 0) {
            this.currentQuestionIndex--;
            this.showQuestion();
        }
    }

    // 下一题
    nextQuestion() {
        if (this.currentQuestionIndex < this.questions.length - 1) {
            this.currentQuestionIndex++;
            // 清除之前的解析显示
            const explanationElement = document.querySelector('.explanation-display');
            if (explanationElement) {
                explanationElement.remove();
            }
            this.showQuestion();
        }
    }

    // 检查多选题答案
    checkMultipleChoiceAnswer(question) {
        const userAnswer = this.userAnswers[question.id];
        if (!userAnswer) return;

        // 计算正确答案的选项数量
        const correctAnswerCount = question.correctAnswer.length;
        const userAnswerCount = userAnswer.length;

        console.log('多选题检查:', {
            questionId: question.id,
            userAnswer: userAnswer,
            userCount: userAnswerCount,
            correctCount: correctAnswerCount,
            correctAnswer: question.correctAnswer
        });

        // 如果用户选择的选项数量等于正确答案的选项数量，则检查答案
        if (userAnswerCount === correctAnswerCount) {
            setTimeout(() => {
                this.checkAnswer(question);
            }, 100);
        } else {
            // 清除之前的解析显示
            const explanationElement = document.querySelector('.explanation-display');
            if (explanationElement) {
                explanationElement.remove();
            }
            
            // 显示提示信息
            this.showMultipleChoiceHint(question, userAnswerCount, correctAnswerCount);
        }
    }

    // 显示多选题提示
    showMultipleChoiceHint(question, userCount, correctCount) {
        // 创建或更新提示显示区域
        let hintElement = document.querySelector('.explanation-display');
        if (!hintElement) {
            hintElement = document.createElement('div');
            hintElement.className = 'explanation-display';
            document.querySelector('.question-content').appendChild(hintElement);
        }

        // 设置提示内容样式
        hintElement.style.marginTop = '20px';
        hintElement.style.padding = '15px';
        hintElement.style.borderRadius = '5px';
        hintElement.style.border = '1px solid #3498db';
        hintElement.style.backgroundColor = '#d6eaf8';
        hintElement.style.color = '#2980b9';

        // 设置提示内容
        hintElement.innerHTML = `
            <div style="font-weight: bold; margin-bottom: 10px;">
                📝 多选题提示
            </div>
            <div>
                您已选择 ${userCount} 个选项，正确答案需要选择 ${correctCount} 个选项。
                <br>请继续选择或取消选择选项，选择完成后将自动显示答案和解析。
            </div>
        `;
    }

    // 检查答案并显示解析
    checkAnswer(question) {
        setTimeout(() => {
            const userAnswer = this.userAnswers[question.id];
            if (!userAnswer) return;

            // 显示所有选项的正确/错误状态
            document.querySelectorAll('.option').forEach(optionElement => {
                const optionLetter = optionElement.dataset.option;
                
                // 移除之前的正确/错误状态
                optionElement.classList.remove('correct', 'incorrect');
                
                // 标记正确答案
                if (question.correctAnswer.includes(optionLetter)) {
                    optionElement.classList.add('correct');
                } 
                // 标记用户选择的错误答案
                else if (userAnswer.includes(optionLetter)) {
                    optionElement.classList.add('incorrect');
                }
            });

            // 检查答案是否正确
            const isCorrect = userAnswer.sort().join('') === question.correctAnswer.split('').sort().join('');
            
            // 如果答案错误，记录错题
            if (!isCorrect) {
                this.addWrongQuestion(question, userAnswer);
            }

            // 显示解析
            this.showExplanation(question, isCorrect);
        }, 100);
    }

    // 显示解析
    showExplanation(question, isCorrect) {
        // 创建或更新解析显示区域
        let explanationElement = document.querySelector('.explanation-display');
        if (!explanationElement) {
            explanationElement = document.createElement('div');
            explanationElement.className = 'explanation-display';
            document.querySelector('.question-content').appendChild(explanationElement);
        }

        // 设置解析内容样式
        explanationElement.style.marginTop = '20px';
        explanationElement.style.padding = '15px';
        explanationElement.style.borderRadius = '5px';
        explanationElement.style.border = '1px solid #ddd';
        explanationElement.style.backgroundColor = isCorrect ? '#d5f5e3' : '#fadbd8';
        explanationElement.style.color = isCorrect ? '#27ae60' : '#e74c3c';

        // 设置解析内容
        explanationElement.innerHTML = `
            <div style="font-weight: bold; margin-bottom: 10px;">
                ${isCorrect ? '✓ 回答正确' : '✗ 回答错误'}
            </div>
            <div>
                <strong>解析：</strong>${question.explanation}
            </div>
        `;
    }

    // 显示错题本
    showWrongQuestions() {
        this.loadWrongQuestions();
        this.updateWrongStats();
        this.displayWrongQuestions();
        this.showScreen('wrong-book');
    }

    // 加载错题数据
    loadWrongQuestions() {
        const wrongData = localStorage.getItem('wrongQuestions');
        this.wrongQuestionDetails = wrongData ? JSON.parse(wrongData) : [];
    }

    // 保存错题数据
    saveWrongQuestions() {
        localStorage.setItem('wrongQuestions', JSON.stringify(this.wrongQuestionDetails));
    }

    // 添加错题
    addWrongQuestion(question, userAnswer) {
        const existingIndex = this.wrongQuestionDetails.findIndex(wq => wq.questionId === question.id);
        const wrongDetail = {
            questionId: question.id,
            questionText: question.text,
            userAnswer: userAnswer.join(', '),
            correctAnswer: question.correctAnswer,
            explanation: question.explanation,
            wrongTime: new Date().toISOString(),
            reviewCount: 0,
            isReviewed: false
        };

        if (existingIndex >= 0) {
            // 更新现有错题
            this.wrongQuestionDetails[existingIndex] = wrongDetail;
        } else {
            // 添加新错题
            this.wrongQuestionDetails.push(wrongDetail);
        }

        this.saveWrongQuestions();
    }

    // 更新错题统计
    updateWrongStats() {
        const totalCount = this.wrongQuestionDetails.length;
        const reviewedCount = this.wrongQuestionDetails.filter(wq => wq.isReviewed).length;
        const accuracyRate = totalCount > 0 ? Math.round((reviewedCount / totalCount) * 100) : 0;

        document.getElementById('total-wrong-count').textContent = totalCount;
        document.getElementById('reviewed-count').textContent = reviewedCount;
        document.getElementById('accuracy-rate').textContent = accuracyRate + '%';
    }

    // 显示错题列表
    displayWrongQuestions() {
        const wrongContainer = document.getElementById('wrong-questions-container');
        
        if (this.wrongQuestionDetails.length === 0) {
            wrongContainer.innerHTML = '<p style="text-align: center; color: #7f8c8d; padding: 40px;">暂无错题记录</p>';
            return;
        }

        wrongContainer.innerHTML = '';

        this.wrongQuestionDetails.forEach((wrongDetail, index) => {
            const question = this.questions.find(q => q.id === wrongDetail.questionId);
            if (!question) return;

            const wrongItem = document.createElement('div');
            wrongItem.className = 'wrong-question-item';
            
            wrongItem.innerHTML = `
                <div class="wrong-question-header">
                    <div class="wrong-question-title">第${index + 1}题</div>
                    <div class="wrong-question-actions">
                        <button class="review-btn" onclick="networkBibleApp.reviewWrongQuestion(${wrongDetail.questionId})">复习</button>
                        <button class="remove-btn" onclick="networkBibleApp.removeWrongQuestion(${wrongDetail.questionId})">移除</button>
                    </div>
                </div>
                <div class="wrong-question-content">
                    <div style="margin-bottom: 10px;">${question.text}</div>
                    <div class="wrong-answer-info">
                        <span class="wrong-user-answer">你的答案: ${wrongDetail.userAnswer}</span>
                        <span class="wrong-correct-answer">正确答案: ${wrongDetail.correctAnswer}</span>
                    </div>
                    <div class="wrong-explanation">
                        <strong>解析：</strong>${wrongDetail.explanation}
                    </div>
                </div>
            `;
            
            wrongContainer.appendChild(wrongItem);
        });
    }

    // 导入题目
    async importQuestions() {
        const importText = document.getElementById('import-text').value.trim();
        if (!importText) {
            this.showImportResult('请输入题目数据或URL地址！', 'error');
            return;
        }

        try {
            let questionData;
            
            // 检查是否是URL
            if (this.isValidUrl(importText)) {
                this.showLoading('正在从网络加载数据...');
                questionData = await this.fetchQuestionsFromUrl(importText);
                this.hideLoading();
            } else {
                // 解析本地输入的JSON数据
                questionData = JSON.parse(importText);
            }

            // 验证数据格式
            if (!Array.isArray(questionData)) {
                throw new Error('数据格式错误：应该是题目数组');
            }

            // 验证每道题目的格式
            questionData.forEach((question, index) => {
                this.validateQuestionFormat(question, index);
            });

            // 生成题库名称
            const questionBankName = this.generateQuestionBankName(questionData);
            
            // 保存到本地存储
            this.saveQuestionBank(questionBankName, questionData);
            
            // 加载新导入的题目
            this.questions = questionData;
            
            this.showImportResult(`成功导入 ${questionData.length} 道题目！题库名称：${questionBankName}`, 'success');
            
            // 清空输入框
            document.getElementById('import-text').value = '';
        } catch (error) {
            this.showImportResult('导入失败：' + error.message, 'error');
        }
    }

    // 检查是否是有效的URL
    isValidUrl(string) {
        try {
            new URL(string);
            return true;
        } catch (_) {
            return false;
        }
    }

    // 从URL获取题目数据
    async fetchQuestionsFromUrl(url) {
        try {
            const response = await fetch(url);
            if (!response.ok) {
                throw new Error(`HTTP错误: ${response.status}`);
            }
            const data = await response.json();
            return data;
        } catch (error) {
            throw new Error(`网络请求失败: ${error.message}`);
        }
    }

    // 验证题目格式
    validateQuestionFormat(question, index) {
        const requiredFields = ['id', 'text', 'options', 'correctAnswer', 'explanation', 'type'];
        const missingFields = requiredFields.filter(field => !question.hasOwnProperty(field));
        
        if (missingFields.length > 0) {
            throw new Error(`第${index + 1}题缺少必要字段: ${missingFields.join(', ')}`);
        }

        if (!Array.isArray(question.options) || question.options.length < 2) {
            throw new Error(`第${index + 1}题选项格式错误`);
        }

        if (!['single', 'multiple'].includes(question.type)) {
            throw new Error(`第${index + 1}题类型错误，应该是'single'或'multiple'`);
        }
    }

    // 生成题库名称
    generateQuestionBankName(questionData) {
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        
        // 尝试从题目内容推断领域
        let domain = 'general';
        const firstQuestion = questionData[0];
        if (firstQuestion && firstQuestion.text) {
            const text = firstQuestion.text.toLowerCase();
            if (text.includes('网络') || text.includes('network')) {
                domain = 'network';
            } else if (text.includes('软件') || text.includes('software')) {
                domain = 'software';
            } else if (text.includes('数据库') || text.includes('database')) {
                domain = 'database';
            } else if (text.includes('算法') || text.includes('algorithm')) {
                domain = 'algorithm';
            }
        }
        
        return `${domain}_${year}${month}${day}`;
    }

    // 保存题库到本地存储
    saveQuestionBank(name, data) {
        const questionBanks = this.getQuestionBanks();
        questionBanks[name] = {
            name: name,
            data: data,
            createTime: new Date().toISOString(),
            questionCount: data.length
        };
        localStorage.setItem('questionBanks', JSON.stringify(questionBanks));
    }

    // 获取所有题库
    getQuestionBanks() {
        const banks = localStorage.getItem('questionBanks');
        return banks ? JSON.parse(banks) : {};
    }

    // 加载指定题库
    loadQuestionBank(bankName) {
        const questionBanks = this.getQuestionBanks();
        if (questionBanks[bankName]) {
            this.questions = questionBanks[bankName].data;
            return true;
        }
        return false;
    }

    // 显示导入结果
    showImportResult(message, type) {
        const resultElement = document.getElementById('import-result');
        resultElement.textContent = message;
        resultElement.className = type;
    }

    // 刷新题库列表
    refreshQuestionBanksList() {
        const questionBanks = this.getQuestionBanks();
        const banksListContainer = document.getElementById('question-banks-list');
        
        if (Object.keys(questionBanks).length === 0) {
            banksListContainer.innerHTML = '<p style="text-align: center; color: #7f8c8d;">暂无题库，请先导入题库</p>';
            return;
        }

        banksListContainer.innerHTML = '';
        
        Object.values(questionBanks).forEach(bank => {
            const bankItem = document.createElement('div');
            bankItem.className = 'question-bank-item';
            bankItem.dataset.bankName = bank.name;
            
            const createTime = new Date(bank.createTime).toLocaleString('zh-CN');
            
            bankItem.innerHTML = `
                <div class="question-bank-name">${bank.name}</div>
                <div class="question-bank-info">
                    题目数量: ${bank.questionCount} | 创建时间: ${createTime}
                </div>
            `;
            
            // 添加点击事件
            bankItem.addEventListener('click', () => {
                this.selectQuestionBank(bank.name);
            });
            
            banksListContainer.appendChild(bankItem);
        });
        
        // 更新按钮状态
        this.updateBankActionButtons();
    }

    // 选择题库
    selectQuestionBank(bankName) {
        // 移除其他题库的选中状态
        document.querySelectorAll('.question-bank-item').forEach(item => {
            item.classList.remove('active');
        });
        
        // 设置当前题库为选中状态
        const selectedItem = document.querySelector(`[data-bank-name="${bankName}"]`);
        if (selectedItem) {
            selectedItem.classList.add('active');
        }
        
        // 更新按钮状态
        this.updateBankActionButtons();
        
        // 加载题库数据
        if (this.loadQuestionBank(bankName)) {
            this.showImportResult(`已选择题库: ${bankName}`, 'success');
        } else {
            this.showImportResult(`加载题库失败: ${bankName}`, 'error');
        }
    }

    // 初始化时显示题库列表
    initQuestionBanksList() {
        this.refreshQuestionBanksList();
    }

    // 删除选中的题库
    deleteSelectedQuestionBank() {
        const selectedBank = document.querySelector('.question-bank-item.active');
        if (!selectedBank) {
            this.showImportResult('请先选择要删除的题库！', 'error');
            return;
        }

        const bankName = selectedBank.dataset.bankName;
        if (confirm(`确定要删除题库 "${bankName}" 吗？此操作不可恢复！`)) {
            const questionBanks = this.getQuestionBanks();
            delete questionBanks[bankName];
            localStorage.setItem('questionBanks', JSON.stringify(questionBanks));
            
            this.refreshQuestionBanksList();
            this.updateBankActionButtons();
            this.showImportResult(`已删除题库: ${bankName}`, 'success');
        }
    }

    // 重命名选中的题库
    renameSelectedQuestionBank() {
        const selectedBank = document.querySelector('.question-bank-item.active');
        if (!selectedBank) {
            this.showImportResult('请先选择要重命名的题库！', 'error');
            return;
        }

        const oldName = selectedBank.dataset.bankName;
        const newName = prompt(`请输入新的题库名称:`, oldName);
        
        if (newName && newName.trim() && newName !== oldName) {
            const questionBanks = this.getQuestionBanks();
            if (questionBanks[newName]) {
                this.showImportResult('题库名称已存在，请使用其他名称！', 'error');
                return;
            }

            // 重命名题库
            questionBanks[newName] = questionBanks[oldName];
            questionBanks[newName].name = newName;
            delete questionBanks[oldName];
            
            localStorage.setItem('questionBanks', JSON.stringify(questionBanks));
            
            this.refreshQuestionBanksList();
            this.showImportResult(`已重命名题库: ${oldName} -> ${newName}`, 'success');
        }
    }

    // 更新题库操作按钮状态
    updateBankActionButtons() {
        const selectedBank = document.querySelector('.question-bank-item.active');
        const deleteBtn = document.getElementById('delete-bank');
        const renameBtn = document.getElementById('rename-bank');
        
        if (selectedBank) {
            deleteBtn.disabled = false;
            renameBtn.disabled = false;
        } else {
            deleteBtn.disabled = true;
            renameBtn.disabled = true;
        }
    }

    // 显示题目图片
    displayQuestionImage(imagePath, container) {
        container.innerHTML = '';
        container.classList.remove('hidden');
        
        // 创建图片元素
        const img = document.createElement('img');
        img.src = imagePath;
        img.alt = '题目图片';
        img.className = 'question-image-content';
        
        // 添加加载状态
        const loadingDiv = document.createElement('div');
        loadingDiv.className = 'image-loading';
        loadingDiv.textContent = '图片加载中...';
        container.appendChild(loadingDiv);
        
        // 图片加载成功
        img.onload = () => {
            container.removeChild(loadingDiv);
            container.appendChild(img);
            
            // 添加图片点击放大功能
            img.addEventListener('click', () => {
                this.showImageModal(imagePath);
            });
        };
        
        // 图片加载失败
        img.onerror = () => {
            container.removeChild(loadingDiv);
            const errorDiv = document.createElement('div');
            errorDiv.className = 'image-error';
            errorDiv.innerHTML = `
                <p>图片加载失败</p>
                <p>路径: ${imagePath}</p>
                <button onclick="this.parentElement.parentElement.classList.add('hidden')">隐藏</button>
            `;
            container.appendChild(errorDiv);
        };
    }

    // 显示图片模态框
    showImageModal(imagePath) {
        // 创建模态框
        const modal = document.createElement('div');
        modal.className = 'image-modal';
        modal.innerHTML = `
            <div class="image-modal-content">
                <span class="image-modal-close">&times;</span>
                <img src="${imagePath}" alt="题目图片">
            </div>
        `;
        
        // 添加到页面
        document.body.appendChild(modal);
        
        // 关闭模态框事件
        const closeBtn = modal.querySelector('.image-modal-close');
        closeBtn.addEventListener('click', () => {
            document.body.removeChild(modal);
        });
        
        // 点击背景关闭
        modal.addEventListener('click', (e) => {
            if (e.target === modal) {
                document.body.removeChild(modal);
            }
        });
        
        // ESC键关闭
        const escHandler = (e) => {
            if (e.key === 'Escape') {
                document.body.removeChild(modal);
                document.removeEventListener('keydown', escHandler);
            }
        };
        document.addEventListener('keydown', escHandler);
    }

    // 复习错题
    reviewWrongQuestion(questionId) {
        const wrongDetail = this.wrongQuestionDetails.find(wq => wq.questionId === questionId);
        if (wrongDetail) {
            wrongDetail.reviewCount++;
            wrongDetail.isReviewed = true;
            this.saveWrongQuestions();
            this.updateWrongStats();
            this.displayWrongQuestions();
        }
    }

    // 移除错题
    removeWrongQuestion(questionId) {
        if (confirm('确定要移除这道错题吗？')) {
            this.wrongQuestionDetails = this.wrongQuestionDetails.filter(wq => wq.questionId !== questionId);
            this.saveWrongQuestions();
            this.updateWrongStats();
            this.displayWrongQuestions();
        }
    }

    // 练习错题
    practiceWrongQuestions() {
        if (this.wrongQuestionDetails.length === 0) {
            alert('暂无错题可练习！');
            return;
        }

        // 创建错题练习题库
        const wrongQuestionIds = this.wrongQuestionDetails.map(wq => wq.questionId);
        this.questions = this.questions.filter(q => wrongQuestionIds.includes(q.id));
        
        if (this.questions.length === 0) {
            alert('错题对应的题目已不存在！');
            return;
        }

        this.currentQuestionIndex = 0;
        this.userAnswers = {};
        this.showQuestion();
        this.showScreen('question-screen');
    }

    // 清空错题本
    clearWrongQuestions() {
        if (this.wrongQuestionDetails.length === 0) {
            alert('错题本已经是空的！');
            return;
        }

        if (confirm('确定要清空所有错题吗？此操作不可恢复！')) {
            this.wrongQuestionDetails = [];
            this.saveWrongQuestions();
            this.updateWrongStats();
            this.displayWrongQuestions();
        }
    }

    // 导出错题
    exportWrongQuestions() {
        if (this.wrongQuestionDetails.length === 0) {
            alert('暂无错题可导出！');
            return;
        }

        const exportData = {
            exportTime: new Date().toISOString(),
            totalCount: this.wrongQuestionDetails.length,
            wrongQuestions: this.wrongQuestionDetails.map(wq => {
                const question = this.questions.find(q => q.id === wq.questionId);
                return {
                    ...wq,
                    question: question ? {
                        text: question.text,
                        options: question.options,
                        type: question.type
                    } : null
                };
            })
        };

        const dataStr = JSON.stringify(exportData, null, 2);
        const dataBlob = new Blob([dataStr], {type: 'application/json'});
        
        const link = document.createElement('a');
        link.href = URL.createObjectURL(dataBlob);
        link.download = `错题本_${new Date().toISOString().split('T')[0]}.json`;
        link.click();
    }

    // 开始模拟考试
    startExam() {
        if (this.questions.length === 0) {
            alert('暂无题目，请先导入题目数据！');
            return;
        }

        // 获取考试设置
        const questionCount = parseInt(document.getElementById('exam-question-count').value);
        this.examTimeLimit = parseInt(document.getElementById('exam-time-limit').value);
        const questionType = document.getElementById('exam-question-type').value;

        // 筛选题目
        let examQuestions = [...this.questions];
        if (questionType !== 'all') {
            examQuestions = examQuestions.filter(q => q.type === questionType);
        }

        if (examQuestions.length === 0) {
            alert('没有符合条件的题目！');
            return;
        }

        // 随机选择题目
        if (examQuestions.length > questionCount) {
            examQuestions = this.shuffleArray(examQuestions).slice(0, questionCount);
        }

        // 设置考试模式
        this.isExamMode = true;
        this.questions = examQuestions;
        this.currentQuestionIndex = 0;
        this.userAnswers = {};
        this.examStartTime = new Date();

        // 开始计时
        this.startExamTimer();

        // 显示考试界面
        this.showQuestion();
        this.showScreen('question-screen');
    }

    // 开始考试计时
    startExamTimer() {
        const timerElement = document.getElementById('exam-timer');
        timerElement.classList.remove('hidden');

        this.examTimer = setInterval(() => {
            const now = new Date();
            const elapsed = Math.floor((now - this.examStartTime) / 1000);
            const remaining = (this.examTimeLimit * 60) - elapsed;

            if (remaining <= 0) {
                this.submitExam();
                return;
            }

            const minutes = Math.floor(remaining / 60);
            const seconds = remaining % 60;
            timerElement.textContent = `剩余时间: ${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;

            // 最后5分钟变红色
            if (remaining <= 300) {
                timerElement.style.color = '#e74c3c';
                timerElement.style.backgroundColor = '#fadbd8';
            }
        }, 1000);
    }

    // 停止考试计时
    stopExamTimer() {
        if (this.examTimer) {
            clearInterval(this.examTimer);
            this.examTimer = null;
        }
        document.getElementById('exam-timer').classList.add('hidden');
    }

    // 提交考试
    submitExam() {
        if (this.isExamMode) {
            this.stopExamTimer();
            this.isExamMode = false;
        }

        // 计算成绩
        const result = this.calculateExamResult();
        this.showExamResult(result);
    }

    // 计算考试结果
    calculateExamResult() {
        let correctCount = 0;
        let totalCount = this.questions.length;
        const wrongQuestions = [];

        this.questions.forEach(question => {
            const userAnswer = this.userAnswers[question.id] || [];
            const isCorrect = userAnswer.sort().join('') === question.correctAnswer.split('').sort().join('');
            
            if (isCorrect) {
                correctCount++;
            } else {
                wrongQuestions.push(question.id);
                this.addWrongQuestion(question, userAnswer);
            }
        });

        const score = Math.round((correctCount / totalCount) * 100);
        const examTime = this.examStartTime ? Math.floor((new Date() - this.examStartTime) / 1000) : 0;

        return {
            score: score,
            correctCount: correctCount,
            totalCount: totalCount,
            wrongCount: wrongQuestions.length,
            examTime: examTime,
            wrongQuestions: wrongQuestions
        };
    }

    // 显示考试结果
    showExamResult(result) {
        const resultContainer = document.getElementById('result-content');
        const timeStr = this.formatTime(result.examTime);
        
        resultContainer.innerHTML = `
            <div class="exam-result-summary">
                <h3>考试结果</h3>
                <div class="result-stats">
                    <div class="stat-item">
                        <span class="stat-label">总分</span>
                        <span class="stat-value">${result.score}分</span>
                    </div>
                    <div class="stat-item">
                        <span class="stat-label">正确题数</span>
                        <span class="stat-value">${result.correctCount}/${result.totalCount}</span>
                    </div>
                    <div class="stat-item">
                        <span class="stat-label">用时</span>
                        <span class="stat-value">${timeStr}</span>
                    </div>
                </div>
                <div class="result-message">
                    ${this.getResultMessage(result.score)}
                </div>
            </div>
        `;

        this.showScreen('result-screen');
    }

    // 获取结果评价
    getResultMessage(score) {
        if (score >= 90) return '优秀！继续保持！';
        if (score >= 80) return '良好！还有提升空间！';
        if (score >= 70) return '及格！需要加强练习！';
        if (score >= 60) return '勉强及格！建议多复习！';
        return '不及格！需要认真学习！';
    }

    // 格式化时间
    formatTime(seconds) {
        const hours = Math.floor(seconds / 3600);
        const minutes = Math.floor((seconds % 3600) / 60);
        const secs = seconds % 60;
        
        if (hours > 0) {
            return `${hours}小时${minutes}分钟${secs}秒`;
        } else if (minutes > 0) {
            return `${minutes}分钟${secs}秒`;
        } else {
            return `${secs}秒`;
        }
    }

    // 数组随机排序
    shuffleArray(array) {
        const shuffled = [...array];
        for (let i = shuffled.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
        }
        return shuffled;
    }

    // 更新进度条
    updateProgress() {
        const totalCount = this.questions.length;
        const currentIndex = this.currentQuestionIndex;
        const progress = Math.round(((currentIndex + 1) / totalCount) * 100);
        
        document.getElementById('progress-fill').style.width = progress + '%';
        document.getElementById('progress-text').textContent = progress + '%';
    }

    // 显示加载动画
    showLoading(text = '加载中...') {
        const overlay = document.getElementById('loading-overlay');
        const loadingText = overlay.querySelector('.loading-text');
        loadingText.textContent = text;
        overlay.classList.remove('hidden');
    }

    // 隐藏加载动画
    hideLoading() {
        document.getElementById('loading-overlay').classList.add('hidden');
    }

    // 处理键盘快捷键
    handleKeyboardShortcuts(e) {
        // 只在题目界面处理快捷键
        if (!document.getElementById('question-screen').classList.contains('hidden')) {
            switch(e.key) {
                case 'ArrowLeft':
                    e.preventDefault();
                    this.prevQuestion();
                    break;
                case 'ArrowRight':
                    e.preventDefault();
                    this.nextQuestion();
                    break;
                case '1':
                case '2':
                case '3':
                case '4':
                case '5':
                case '6':
                    e.preventDefault();
                    this.selectOptionByNumber(parseInt(e.key) - 1);
                    break;
                case 'Enter':
                    if (this.isExamMode) {
                        e.preventDefault();
                        this.submitExam();
                    }
                    break;
            }
        }
    }

    // 通过数字键选择选项
    selectOptionByNumber(index) {
        const options = document.querySelectorAll('.option');
        if (options[index]) {
            options[index].click();
        }
    }

    // 加载应用设置
    loadAppSettings() {
        const defaultSettings = {
            theme: 'light',
            autoSave: true,
            showHints: true,
            soundEnabled: false,
            lastUsedBank: null,
            examSettings: {
                questionCount: 50,
                timeLimit: 60,
                questionType: 'all'
            }
        };

        const savedSettings = localStorage.getItem('appSettings');
        return savedSettings ? { ...defaultSettings, ...JSON.parse(savedSettings) } : defaultSettings;
    }

    // 保存应用设置
    saveAppSettings() {
        localStorage.setItem('appSettings', JSON.stringify(this.appSettings));
    }

    // 更新应用设置
    updateAppSetting(key, value) {
        this.appSettings[key] = value;
        this.saveAppSettings();
    }

    // 导出所有数据
    exportAllData() {
        const allData = {
            exportTime: new Date().toISOString(),
            version: '1.0.0',
            questionBanks: this.getQuestionBanks(),
            wrongQuestions: this.wrongQuestionDetails,
            appSettings: this.appSettings
        };

        const dataStr = JSON.stringify(allData, null, 2);
        const dataBlob = new Blob([dataStr], {type: 'application/json'});
        
        const link = document.createElement('a');
        link.href = URL.createObjectURL(dataBlob);
        link.download = `网规宝典数据备份_${new Date().toISOString().split('T')[0]}.json`;
        link.click();
    }

    // 导入所有数据
    async importAllData(file) {
        try {
            const text = await file.text();
            const data = JSON.parse(text);
            
            if (data.questionBanks) {
                localStorage.setItem('questionBanks', JSON.stringify(data.questionBanks));
            }
            
            if (data.wrongQuestions) {
                localStorage.setItem('wrongQuestions', JSON.stringify(data.wrongQuestions));
            }
            
            if (data.appSettings) {
                localStorage.setItem('appSettings', JSON.stringify(data.appSettings));
                this.appSettings = this.loadAppSettings();
            }
            
            this.refreshQuestionBanksList();
            this.showImportResult('数据导入成功！', 'success');
        } catch (error) {
            this.showImportResult('数据导入失败：' + error.message, 'error');
        }
    }

    // 清空所有数据
    clearAllData() {
        if (confirm('确定要清空所有数据吗？此操作不可恢复！')) {
            localStorage.clear();
            this.questions = [];
            this.wrongQuestionDetails = [];
            this.appSettings = this.loadAppSettings();
            this.refreshQuestionBanksList();
            this.showImportResult('所有数据已清空！', 'success');
        }
    }
}

// 页面加载完成后初始化应用
document.addEventListener('DOMContentLoaded', () => {
    window.networkBibleApp = new NetworkBibleApp();
});